﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EzFrameWork;
using System;
using System.Text;
using System.Threading;

public class TcpSever : MonoBehaviour
{
    public int Port = 12312;
    EzTCPSever tCPSever;
    // Start is called before the first frame update
    void Start()
    {
        tCPSever = new EzTCPSever(Port, 0);
        tCPSever.StartServer();
        tCPSever.Response += Response;
    }

    private void OnApplicationQuit()
    {
        if (tCPSever!=null)
        {
            tCPSever.CloseServer();
        }
    }
    //服务器接受用户消息
    private void Response(MessageType arg1, byte[] arg2)
    {
        string str;
        switch (arg1)
        {
            case MessageType.HERTPACK:
                Hert hert = EzDataRWS.BytesToObject<Hert>(arg2);
                Debug.Log("服务器接受到客户端：" + hert.ID + "的心跳包");
                tCPSever.SendData(hert.ID, MessageType.HERTPACK, arg2);
                break;
            case MessageType.FILE:

                break;
            case MessageType.JSON:
                str = Encoding.UTF8.GetString(arg2);
                JsonUtility.FromJson<DataPack>(str);
                break;
            case MessageType.SENDID:
                str = Encoding.UTF8.GetString(arg2);
                Debug.Log(str);
                break;
            case MessageType.TEXT:
                break;
            case MessageType.BYE:
                break;
            default:
                break;
        }
    }

    private void OnGUI()
    {
        tCPSever.ShowSeverIP();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            tCPSever.SendAllSockets(MessageType.TEXT, Encoding.UTF8.GetBytes("1212"));
            Debug.Log("发送成功");
        }
    }
    void OnDistory()
    {

    }
}
